package com.styytech.dadabao.ui.main;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.styytech.dadabao.DadaApplication;
import com.styytech.dadabao.R;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.constant.ConstantsCommon;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.ui.home.HomeFragment;
import com.styytech.dadabao.ui.login.LoginActivity;
import com.styytech.dadabao.ui.more.MoreFragment;
import com.styytech.dadabao.ui.my.MyFragment;
import com.styytech.dadabao.ui.project.ProjectFragment;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.utils.UpdateAppUtils;

import java.util.List;


@ContentView(R.layout.activity_main_dadabao)
public class MainActivity extends BaseActivity {

    public final static int ID_HOME = R.id.tv_home;
    public final static int ID_PROJECT = R.id.tv_project;
    public final static int ID_MY = R.id.tv_my;
    public final static int ID_MORE = R.id.tv_more;

//
//    @ViewInject(R.id.tv_topBar_Title)
//    private TextView tv_topBar_Title;
    /**
     * 标题
     */
    @ViewInject(ID_HOME)
    private TextView tv_home;
    @ViewInject(ID_PROJECT)
    TextView tv_project;
    @ViewInject(ID_MY)
    TextView tv_my;
    @ViewInject(ID_MORE)
    TextView tv_more;


    private Context context;
    /**
     * 记录点击item的Id
     */
    private int itemId = 0;
    private HomeFragment homeFragment = null;
    private ProjectFragment projectFragment = null;
    private MyFragment myFragment = null;
    private MoreFragment moreFragment = null;

    /**
     * 用于对Fragment进行管理
     */
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }

    private void initData() {
        context = this;
        fragmentManager = getSupportFragmentManager();
        new UpdateAppUtils(this).checkingVersion();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        DadaApplication.addActivity(this);
        initFragment();
        initWithApiKey();
        setTopBar(resources.getString(R.string.main_top_home));
    }

    /**
     * 如果没有绑定百度云，则绑定，并记录在属性文件中,以apikey的方式绑定
     */
    private void initWithApiKey() {
//        PushManager.startWork(getApplicationContext(),
//                PushConstants.LOGIN_TYPE_API_KEY, "P13PNa1UcABYGqbjt9UIilOQ");
    }

    /**
     * 设置Fragment，显示主界面
     */
    private void initFragment() {
        //默认页
        itemId = ID_HOME;
        changeStatus(itemId);
        setTabSelection(itemId);// 第一次启动时选中第0个tab

    }
    public void gotoClass2() {
        itemId = ID_PROJECT;
        changeStatus(ID_PROJECT);// 修改item状态
        setTabSelection(ID_PROJECT);

    }
    /**
     * 点击事件
     */
    @OnClick({ID_HOME, ID_MY, ID_PROJECT, ID_MORE})
    public void onFragmentClick(View view) {
        if (view.getId() == ID_MY) {  //如果是我的界面
            if (SpUser.getUserToken(MainActivity.this) == null) { //没有登录
                CommonUtils.startActivity(MainActivity.this, LoginActivity.class);
                return;
            }
        }
        if (itemId == view.getId()) {
            return;
        } else {
            itemId = view.getId();
        }
        changeStatus(itemId);// 修改item状态
        setTabSelection(itemId);
    }
    /**
     * 更换图片/修改字体颜色/背景颜色
     */
    private void changeStatus(int itemId) {
        /**
         * 首页
         */
        if (itemId == ID_HOME) {
            tv_home.setCompoundDrawablesWithIntrinsicBounds(0,
                    R.drawable.ic_tab_home_sel, 0, 0);
            setTextBold(tv_home, true);
        } else {
            tv_home.setCompoundDrawablesWithIntrinsicBounds(0,
                    R.drawable.ic_tab_home_no, 0, 0);
            setTextBold(tv_home, false);
        }

        /**
         * 项目
         */
        if (itemId == ID_PROJECT) {
            tv_project.setCompoundDrawablesWithIntrinsicBounds(0,
                    R.drawable.ic_tab_project_sel, 0, 0);
            setTextBold(tv_project, true);
        } else {
            tv_project.setCompoundDrawablesWithIntrinsicBounds(0,
                    R.drawable.ic_tab_project_no, 0, 0);
            setTextBold(tv_project, false);
        }


        /**
         * 我的
         */
        if (itemId == ID_MY) {
            tv_my.setCompoundDrawablesWithIntrinsicBounds(0,
                    R.drawable.ic_tab_my_sel, 0, 0);
            setTextBold(tv_my, true);
        } else {
            tv_my.setCompoundDrawablesWithIntrinsicBounds(0,
                    R.drawable.ic_tab_my_no, 0, 0);
            setTextBold(tv_my, false);
        }

        /**
         * 更多
         */
        if (itemId == ID_MORE) {
            tv_more.setCompoundDrawablesWithIntrinsicBounds(0,
                    R.drawable.ic_tab_more_sel, 0, 0);
            setTextBold(tv_more, true);
        } else {
            tv_more.setCompoundDrawablesWithIntrinsicBounds(0,
                    R.drawable.ic_tab_more_no, 0, 0);
            setTextBold(tv_more, false);
        }
    }

    /**
     * 设置颜色
     *
     * @param tv
     * @param isSelect 是否选中
     */
    private void setTextBold(TextView tv, boolean isSelect) {
        if (tv == null) return;
        if (isSelect) { //选中
            tv.setTextColor(resources.getColor(R.color.main_table_sele));
        } else {
            tv.setTextColor(resources.getColor(R.color.main_table_no));
        }
    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     *
     * @param index 每个tab页对应的下标。ID_HOME 表示首页，ID_PROJECT 项目，ID_MY 我的，ID_MORE 更多
     */
    private void setTabSelection(int index) {
        // 开启一个Fragment事务
        transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case ID_HOME:
                setTopBar(resources.getString(R.string.main_top_home));
                homeFragment = (HomeFragment) fragmentManager
                        .findFragmentByTag("ID_HOME");

                if (homeFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.fl_content, homeFragment, "ID_HOME");
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    homeFragment.tabreloadBtnOnclick();
                    transaction.show(homeFragment);
                }
                break;
            case ID_PROJECT:
                setTopBar(resources.getString(R.string.main_top_project));
                projectFragment = (ProjectFragment) fragmentManager
                        .findFragmentByTag("ID_PROJECT");
                if (projectFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    String newsUrl = ConstantsServerUrl.getProductListUrl();
                    projectFragment = ProjectFragment.newInstance(newsUrl,
                            ConstantsCommon.DATA_SRC_PROJECT,
                            ConstantsCommon.ADAPTER_TYPE_PROJECT, null);
                    transaction.add(R.id.fl_content, projectFragment, "ID_PROJECT");
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(projectFragment);
                }
                break;
            case ID_MY:
                setTopBar(resources.getString(R.string.main_top_my));
                myFragment = (MyFragment) fragmentManager
                        .findFragmentByTag("ID_MY");
                if (myFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    myFragment = new MyFragment();
                    transaction.add(R.id.fl_content, myFragment, "ID_MY");
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(myFragment);
                }
                break;
            case ID_MORE:
                setTopBar(resources.getString(R.string.main_top_more));
                moreFragment = (MoreFragment) fragmentManager
                        .findFragmentByTag("ID_MORE");
                if (moreFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    moreFragment = new MoreFragment();
                    transaction.add(R.id.fl_content, moreFragment, "ID_MORE");
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(moreFragment);
                }
                break;
        }
        transaction.commit();
    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        List<Fragment> fList = fragmentManager.getFragments();
        if (fList == null) {
            return;
        }
        for (Fragment fragment : fList) {
            if (fragment != null) {
                transaction.hide(fragment);
            }
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                DadaApplication.exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
